package se.topshelf.golftracker.web.controller.round;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import se.topshelf.golftracker.core.domain.Round;
import se.topshelf.golftracker.core.service.BaseService;
import se.topshelf.golftracker.web.validator.BaseEntityValidator;

/**
 * Validates Round entities, so that they are ok save.
 */
public class RoundValidator extends BaseEntityValidator<Round> {
    public static final String PLAYER_FIELD_NAME = "player";
    public static final String TEE_COLOUR_FIELD_NAME = "teeColour";
    public static final String TEE_TIME_FIELD_NAME = "teeTime";
    private BaseService baseService;


    public RoundValidator(BaseService baseService) {
        super(Round.class);
        this.baseService = baseService;
    }


    @Override
    protected void validateFields(Round entityToCheck, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, TEE_TIME_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        if( entityToCheck.getTeeTime().getRounds().size() >= entityToCheck.getTeeTime().getMaxParticipants() && entityToCheck.getId() == null){
            errors.reject("fullyBooked", "The tee time is fully booked, no player round can be added.");
        }
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, TEE_COLOUR_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, PLAYER_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
    }

    @Override
    protected BaseService getBaseService() {
        return baseService;
    }

    @Override
    protected boolean isNaturalKeyEqual(Round savedEntity, Round entityToCheck) {
        //If any combination matches
        return savedEntity.getTeeTime().equals(entityToCheck.getTeeTime()) &&
                savedEntity.getPlayer().equals(entityToCheck.getPlayer());
    }

    @Override
    protected void doRejectOfNaturalField(Errors errors, Round entityToCheck) {
        errors.reject("duplicate", "The Player is already part of the round");
    }
}
